import sys
import socket
import functools

from . import sdbapi

from warnings import warn

def __func__():
    return sys._getframe().f_back.f_code.co_name

def send(sock, data):
    sent = 0
    while sent < len(data):
        sent += sock.send(data[sent:])
    print 'SEND:', len(data), repr(data)

def recv(sock, length):
    buff = ''
    while len(buff) < length:
        buff += sock.recv(length - len(buff))
    print 'RECV:', len(data), repr(data)
    return buff

class client(object):
    def __init__(self, host='localhost', service=11810, user='', psw=''):
        self._host = host
        self._service = service
        self._user = user
        self._psw = psw

        self._do_connect()

    def _do_connect(self):
        self._conn = sdbapi.Connection()
        self._conn.connect((self._host, self._service))
        self._conn.check_user(self._user, self._psw)

#    def connect(self, host, service, **kw):
#        self._host = host
#        self._port = port
#
#    def connect_to_hosts(self, hosts, **kwargs):
#        pass

    def create_collection_space(self, cs_name, page_size=0):
        cs = sdb_create_collection_space(self._conn, cs_name, page_size)
        return cs

    def drop_collection_space(self, cs_name):
        return self._conn.drop_collection_space(cs_name)

    def disconnect(self):
        self._conn.close()
        self._conn = None

def sdb_get_version():
    return sdbapi.get_version()

def sdb_create_client():
    return client()

def sdb_create_collection_space(conn, cs_name, page_size):
    return sdbapi.create_collection_space(conn, cs_name, page_size)

def sdb_release_client(clt):
    warn('%s is not implemented yet.' % __func__(), UserWarning, stacklevel=2)
    pass

def sdb_connect(*a, **kw):
    warn('%s is not implemented yet.' % __func__(), UserWarning, stacklevel=2)
    pass
